package com.hmdp.service.impl;

import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.util.StrUtil;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.hmdp.dto.Result;
import com.hmdp.dto.UserDTO;
import com.hmdp.entity.Blog;
import com.hmdp.entity.Follow;
import com.hmdp.entity.ScrollResult;
import com.hmdp.entity.User;
import com.hmdp.mapper.BlogMapper;
import com.hmdp.service.IBlogService;
import com.hmdp.service.IFollowService;
import com.hmdp.service.IUserService;
import com.hmdp.utils.RedisConstants;
import com.hmdp.utils.SystemConstants;
import com.hmdp.utils.UserHolder;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.data.redis.core.ZSetOperations;
import org.springframework.stereotype.Service;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;
import java.util.*;
import java.util.stream.Collectors;

/**
 * <p>
 *  服务实现类
 * </p>
 *
 * @author 虎哥
 * @since 2021-12-22
 */

@Service
public class BlogServiceImpl extends ServiceImpl<BlogMapper, Blog> implements IBlogService {
    @Resource
    private IUserService userService;
    @Resource
    private StringRedisTemplate stringRedisTemplate;
    @Resource
    private IFollowService followService;
    @Resource
    private IBlogService blogService;
    @Override
    public Result queryHotBlog(Integer current) {
        // 根据用户查询
        Page<Blog> page = query()
                .orderByDesc("liked")
                .page(new Page<>(current, SystemConstants.MAX_PAGE_SIZE));
        // 获取当前页数据
        List<Blog> records = page.getRecords();
        // 查询用户
        records.forEach(blog -> {
            this.queryBlogUser(blog);
//            设置blog类的属性
            this.setIsLike( blog);
        });
        return Result.ok(records);
    }

    private void queryBlogUser(Blog blog) {
        Long userId = blog.getUserId();
        User user = userService.getById(userId);
        blog.setName(user.getNickName());
        blog.setIcon(user.getIcon());
    }

    @Override
    public Result queryBlogById(Long id) {
//        查询blog
        Blog blog = getById(id);
        if (blog==null){
            return Result.fail("笔记不存在");
        }
//         2. 查询blog有关的用户
        queryBlogUser(blog);
        setIsLike( blog);
        return Result.ok(blog);
    }

    private void setIsLike(Blog blog) {
        //        设置isLike属性
        String key = RedisConstants.BLOG_LIKED_KEY+ blog.getId();
        //        获取登录用户
        Long userId = UserHolder.getUser().getId();
        Double score = stringRedisTemplate.opsForZSet().score(key, userId.toString());
//        设置isLike属性
        blog.setIsLike(score!=null);
    }

    @Override
    public Result likeBlog(Long id) {
//        获取登录用户
        UserDTO user = UserHolder.getUser();
        if (user==null){
            return Result.fail("请先登录");
        }
        Long userId = user.getId();

        String key = RedisConstants.BLOG_LIKED_KEY+id;
//        判断当前登录用户是否已经点赞
        Double score = stringRedisTemplate.opsForZSet().score(key, userId.toString());
        if (score==null) {
//        如果未点赞 那么可以点赞
            boolean isSuccess = update().setSql("liked=liked + 1 ").eq("id", id).update();
            if (isSuccess) {
                stringRedisTemplate.opsForZSet().add(key, String.valueOf(userId),System.currentTimeMillis());
            }
        }else {
//        如果已经点赞，那么取消点赞
            boolean isSuccess = update().setSql("liked=liked - 1 ").eq("id", id).update();
            if (isSuccess) {
                stringRedisTemplate.opsForZSet().remove(key, String.valueOf(userId));
            }
        }
        return Result.ok();
    }

    @Override
    public Result queryBlogLikes(Long id) {
        String key = RedisConstants.BLOG_LIKED_KEY+id;
//        从Redis中找出前五个点赞用户ID
        Set<String> top = stringRedisTemplate.opsForZSet().range(key, 0, 4);
        if (top==null||top.isEmpty()) {
            return Result.ok(Collections.emptyList());
        }
//        将set集合转换为list集合
        List<Long> collect = top.stream().map(Long::valueOf).collect(Collectors.toList());
//        从数据库中查询到User集合 但是这里要说明一点
//        在数据库中用IN关键字 查询出的结果会自动排序  所以我们需要用ORDER BY
        String join = StrUtil.join(",", collect);

        List<UserDTO> users = userService.query().in("id", collect).last("ORDER BY FIELD(id,"+join+")").list()
                .stream()
                .map(user-> BeanUtil.copyProperties(user,UserDTO.class))
                .collect(Collectors.toList());

        return Result.ok(users);
    }

    @Override
    public Result saveBlog(Blog blog) {
//        获取登录用户
        UserDTO user = UserHolder.getUser();
        Long userId = user.getId();
        blog.setUserId(user.getId());
//        保存探店笔记
        boolean isSave = blogService.save(blog);
        if (!isSave){
            return Result.fail("保存探店笔记失败");
        }
//        查询笔记作者的所有粉丝
        List<Follow> follows = followService.query().eq("follow_user_id", userId).list();
//        推送笔记ID给所有粉丝
        for (Follow follow : follows) {
            Long followId = follow.getUserId();
            String key = "feed:"+followId;
            stringRedisTemplate.opsForZSet().add(key, blog.getId().toString(),System.currentTimeMillis());
        }
        return Result.ok(blog.getId());
    }


    @Override
    public Result queryBlogOfFollow(Long maxTimeStamp, Integer offset) {
//        获取当前用户id
        Long id = UserHolder.getUser().getId();
//        根据id查询Redis 的feed  返回整个blogId+score
        Set<ZSetOperations.TypedTuple<String>> typedTuples = stringRedisTemplate.opsForZSet().reverseRangeByScoreWithScores(RedisConstants.FEED_KEY + id, 0, maxTimeStamp);
        if (typedTuples==null||typedTuples.isEmpty()){
            return Result.ok();
        }
//        我们需要将feed中的value封装为ids
        List<Long> ids = new ArrayList<>(typedTuples.size());
        long minTime =0;
        int count = 1;
        for (ZSetOperations.TypedTuple<String> typedTuple : typedTuples) {
            String value = typedTuple.getValue();
            ids.add(Long.valueOf(value));
            long time = Objects.requireNonNull(typedTuple.getScore()).longValue();

            if (time==minTime){
                count++;
            }else {
                minTime=time;
                count=1;
            }
        }

//        根据id查询blog
        String join = StrUtil.join(",", ids);


        List<Blog> blogs = query().in("id", ids).last("ORDER BY FIELD(id," + join + ")").list();
        for (Blog blog : blogs) {
            queryBlogUser(blog);
            setIsLike(blog);
        }
//        封装并返回
        ScrollResult scrollResult = new ScrollResult();
        scrollResult.setList(blogs);
        scrollResult.setOffset(count);
        scrollResult.setMinTime(minTime);

        return Result.ok(scrollResult);
    }
}
